//
//  MKDatePickerView.m
//  365money-iOS
//
//  Created by alchemy on 2021/3/25.
//  Copyright © 2021 Cosmic Co,.Ltd. All rights reserved.
//

#import "MKDatePickerView.h"
#import "MGRecordsSwitchView.h"

#import "MKDatePickerWeekendCell.h"
#import "MKDateMonthCell.h"

@interface MKDatePickerView ()
@property (nonatomic, strong) UIButton *preDateButton, *nextDateButton;
@property (nonatomic, strong) UILabel *dateTimeLabel;
@property (nonatomic, strong) MGRecordsSwitchView *categorySwitchView, *accountSwitchView;
// 选中的账户与类型
@property (nonatomic) NSUInteger selectCategoryUniqueId;
@property (nonatomic) NSUInteger selectAccountUniqueId;

@end

@implementation MKDatePickerView

- (instancetype)init {
    self = [super init];
    if (!self) return nil;
    
    @weakify(self);
    self.firstStringLabel = [UILabel createAtSuperView:self fontValue:FONT_REGULAR(16) textColor:TEXT_COLOR_FIRST constraintBlock:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.top.equalTo(self).offset(25);
    } configureBlock:nil];
    
    self.preDateButton = [UIButton createAtSuperView:self constraintBlock:^(MASConstraintMaker *make) {
        make.right.equalTo(self.firstStringLabel.mas_left).offset(-15);
        make.centerY.equalTo(self.firstStringLabel);
        make.size.mas_equalTo(CGSizeMake(35, 35));
    } configureBlock:^(UIButton *view) {
        [view configBackgroundImageWithNormalState:@"date_previous" selectedImage:@"date_previous"];
    } tapedBlock:^(UIButton *view) {
        @strongify(self);
        [self previousMonth];
    }];
    
    self.nextDateButton = [UIButton createAtSuperView:self constraintBlock:^(MASConstraintMaker *make) {
        make.left.equalTo(self.firstStringLabel.mas_right).offset(15);
        make.centerY.equalTo(self.firstStringLabel);
        make.size.mas_equalTo(CGSizeMake(35, 35));
    } configureBlock:^(UIButton *view) {
        [view configBackgroundImageWithNormalState:@"date_next" selectedImage:@"date_next"];
    } tapedBlock:^(UIButton *view) {
        @strongify(self);
        [self nextMonth];
    }];
    
    self.weekendCollectionView = [UICollectionView createAtSuperView:self delegeteTarget:self constraintBlock:^(MASConstraintMaker *make) {
        make.top.equalTo(self).offset(60);
        make.left.right.equalTo(self);
        make.height.mas_equalTo(50);
    } dequeueCellIdentifiers:@[@"MKDatePickerWeekendCell"] configureBlock:^(UICollectionView *view, UICollectionViewFlowLayout *layout) {
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.itemSize = CGSizeMake((kScreenWidth - 20) / 7, 50);
        
        view.contentInset = UIEdgeInsetsMake(0, 10, 0, 10);
    }];
    
    self.collectionView = [UICollectionView createAtSuperView:self delegeteTarget:self constraintBlock:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(300);
        make.left.right.equalTo(self);
        make.top.equalTo(self.weekendCollectionView.mas_bottom);
    } dequeueCellIdentifiers:@[@"MKDateMonthCell"] configureBlock:^(UICollectionView *view, UICollectionViewFlowLayout *layout) {
        layout.itemSize = CGSizeMake(kScreenWidth, 50 * 6);
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        view.pagingEnabled = YES;
        view.showsVerticalScrollIndicator = NO;
        view.showsHorizontalScrollIndicator = NO;
    }];

    self.accountSwitchView = [MGRecordsSwitchView createViewAtSuperView:self constraintBlock:nil configureBlock:nil];
    [self.accountSwitchView cornerRadius:14 width:1 color:APP_COLOR_SAPERATE];
    self.accountSwitchView.tapedActionBlock = ^{
        @strongify(self);
        if (self.accountTapedBlock) {
            self.accountTapedBlock();
        }
    };
    
    self.categorySwitchView = [MGRecordsSwitchView createViewAtSuperView:self constraintBlock:nil configureBlock:nil];
    [self.categorySwitchView cornerRadius:14 width:1 color:APP_COLOR_SAPERATE];
    self.categorySwitchView.tapedActionBlock = ^{
        @strongify(self);
        if (self.categoryTapedBlock) {
            self.categoryTapedBlock();
        }
    };
    
    [UIView createBottomSeparateViewAtSuperView:self color:APP_COLOR_SAPERATE height:1 edgeInsets:UIEdgeInsetsMake(0, 0, 68, 0)];
    [self configViewWithAccountUniqueId:0 categoryUniqueId:0];
    
    return self;
}

- (void)configViewWithAccountUniqueId:(NSUInteger)accountUniqueId categoryUniqueId:(NSUInteger)categoryUniqueId
{
    NSString *accountStr = @"全部账户";
    if (accountUniqueId != 0) {
        MGAccountModel *accountModel = [MGAccountAccessor.shared getAccountModelWithUniqueId:accountUniqueId];
        if (accountModel) {
            accountStr = accountModel.name;
        }
    }
    
    [self.accountSwitchView configViewWithTitleValue:accountStr];
    CGFloat accountWidth = [accountStr sizeWithFont:FONT_REGULAR(12) lineSpacing:0 size:CGSIZE_MAX].width;
    [self.accountSwitchView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(15);
        make.bottom.equalTo(self).offset(-20);
        make.size.mas_equalTo(CGSizeMake(accountWidth + 32, 28));
    }];
    
    NSString *categoryStr = @"全部分类";
    if (categoryUniqueId != 0) {
        MGCategoryModel *categoryModel = [MGCategoryAccessor.shared getCategoryModelWithUniqueId:categoryUniqueId];
        if (categoryModel) {
            categoryStr = categoryModel.name;
        }
    }
    
    [self.categorySwitchView configViewWithTitleValue:categoryStr];
    CGFloat categoryWidth = [categoryStr sizeWithFont:FONT_REGULAR(12) lineSpacing:0 size:CGSIZE_MAX].width;
    [self.categorySwitchView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.accountSwitchView.mas_right).offset(10);
        make.top.equalTo(self.accountSwitchView);
        make.size.mas_equalTo(CGSizeMake(categoryWidth + 32, 28));
    }];
}

- (void)previousMonth
{
    NSInteger index = self.collectionView.contentOffset.x / CGRectGetWidth(self.collectionView.frame);
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:index - 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}

- (void)nextMonth
{
    NSInteger index = self.collectionView.contentOffset.x / CGRectGetWidth(self.collectionView.frame);
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:index + 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}

- (void)scrollToCurrentDate
{
    NSDate *nowDate = [NSDate date];
    self.firstStringLabel.text = [nowDate toStringWithFormatter:@"yyyy/M"];
    [self performSelector:@selector(performScrollAction) afterDelay:0];
}

- (void)scrollToDate:(NSDate *)date
{
    self.firstStringLabel.text = [date toStringWithFormatter:@"yyyy/M"];
    [self performSelector:@selector(performScrollAction) afterDelay:0];
}

- (void)performScrollAction
{
    NSDate *beginDate = [NSDate dateWithTimeIntervalSince1970:0];
    NSDate *nowDate = [NSDate date];
    NSInteger month = [NSDate differenceWithUnit:NSCalendarUnitMonth date:beginDate toOtherDate:nowDate].month;
    
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:month inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView == self.weekendCollectionView) {
        return 7;
    }
    
    NSDate *beginDate = [NSDate dateWithTimeIntervalSince1970:0];
    NSInteger year = [NSDate differenceWithUnit:NSCalendarUnitYear date:beginDate toOtherDate:[NSDate date]].year;
    return (year + 20) * 12;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.weekendCollectionView) {
        MKDatePickerWeekendCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MKDatePickerWeekendCell" forIndexPath:indexPath];
        [cell configViewWithTitleValue:[@[@"周一",@"周二",@"周三",@"周四",@"周五",@"周六",@"周日"] objectAtIndex:indexPath.row]];
        return cell;
    }
    
    NSDate *beginDate = [NSDate dateWithTimeIntervalSince1970:0];
    NSDate *currentDate = [beginDate dateByAddingMonths:indexPath.row].startDayOfMonth;
    
    MKDateMonthCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MKDateMonthCell" forIndexPath:indexPath];
    [cell configViewWithDataModel:currentDate];
    
    @weakify(self);
    cell.dateSelectedBlock = ^(NSDate * _Nonnull date) {
        @strongify(self);
        if (self.dateSelectedBlock) {
            self.dateSelectedBlock(date);
        }
        
        [self.collectionView reloadData];
    };
    
    cell.dateSelectStatusBlock = ^BOOL(NSDate * _Nonnull date) {
        return self.dateSelectStatusBlock(date);
    };
    
    return cell;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offset = scrollView.contentOffset.x;
    CGFloat width = CGRectGetWidth(scrollView.frame);
    NSInteger index = offset / width;
    NSDate *date = [[NSDate dateWithTimeIntervalSince1970:0] dateByAddingMonths:index];
    
    self.firstStringLabel.text = [date toStringWithFormatter:@"yyyy年M月"];
}

@end
